<!--
 * @Author: Bobby
 * @Date: 2022-03-15 18:03:05
 * @LastEditTime: 2022-03-15 18:03:34
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiDownload\uiDownload.vue
 * @CIMC-V2
-->
<template>
  <div class="mr-1" :class="{ hidden: conditionProperty.hidden || info.extension.hidden.value }">
    <el-button
      :ref="info._id"
      v-ui-ref="vSetRef"
      :circle="info.extension.circle.value"
      :disabled="conditionProperty.disabled || info.extension.disabled.value"
      :plain="info.extension.plain.value"
      :round="info.extension.round.value"
      :size="info.extension.size.value"
      :type="info.extension.type.value"
      @click="openDownload"
    >
      <vui-icon v-if="info.extension.icon.value" :icon="info.extension.icon.value" />
      <template v-if="!info.extension.circle.value">
        {{ info.extension.value.value }}
      </template>
    </el-button>
    <!-- 导出配置弹框 -->
    <el-dialog v-if="showModal" v-model="showModal" :append-to-body="true" :title="translateTitle('Ve.elements.导出数据')" :width="'520px'">
      <!-- <template #title>导出数据</template> -->
      <div class="modal-body overflow-hidden w-[500px] min-h-[320px]">
        <div class="overflow-y-scroll scrollbar--light h-80">
          <el-form ref="subForm" class="demo-dynamic" label-width="100px" :model="subForm">
            <el-form-item :label="translateTitle('Ve.elements.文件名')">
              <input v-model="subForm['#EXPORT_FILE_NAME#']" class="p-1 bg-gray-50" />
            </el-form-item>
            <el-form-item :label="translateTitle('Ve.elements.保存类型')">
              <input v-model="subForm['#EXPORT_FILE_TYPE#']" class="p-1 bg-gray-50" disabled />
            </el-form-item>
            <el-form-item
              v-if="info.extension.detailDownload && info.extension.detailDownload.value"
              :label="translateTitle('Ve.elements.是否导出明细')"
            >
              <el-select v-model="subForm.isDetail" :placeholder="translateTitle('Ve.elements.请选择')">
                <el-option v-for="item in optionsDetail" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item :label="translateTitle('Ve.elements.选择数据')">
              <el-select v-model="subForm.type" :placeholder="translateTitle('Ve.elements.请选择')">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item
              v-show="subForm.type == '3' && tableOptions.length > 1 && subForm.isDetail == '1'"
              :label="translateTitle('Ve.elements.选择表格')"
            >
              <el-select v-model="subForm.tableId" :placeholder="translateTitle('Ve.elements.请选择')" @change="tableChange">
                <el-option v-for="item in tableOptions" :key="item._id" :label="item.name" :value="item._id" />
              </el-select>
            </el-form-item>
            <el-form-item :label="translateTitle('Ve.elements.选择字段')">
              <div class="overflow-y-auto" style="height: 200px">
                <div v-if="isMultistage">
                  <el-tree ref="channelTree" :data="treeData" node-key="_id" :props="props" show-checkbox @check="handleCheckChange" />
                </div>
                <div v-for="(item, index) in columnsData" v-else :key="index">
                  <el-checkbox v-model="item.checked">{{ item.title }}</el-checkbox>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- <template #footer> -->
      <div class="flex justify-center p-3 border-t border-gray-100">
        <el-button type="success" @click="save">{{ translateTitle('Ve.elements.导出') }}</el-button>
      </div>
      <!-- </template> -->
    </el-dialog>
  </div>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { defineComponent } from 'vue'
  import { UiMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import { export_json_to_excel } from '@ve/utils/exportExcel'
  import cloneDeep from 'lodash/cloneDeep'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import { exportData } from './sheet'
  export default defineComponent({
    name: 'UiDownload',
    components: {},
    mixins: [UiMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        props: {
          label: 'title',
          children: 'children',
        },
        treeData: [],
        options: [
          {
            value: '1',
            label: this.translateTitle('Ve.elements.当前数据'),
          },
          {
            value: '2',
            label: this.translateTitle('Ve.elements.选中数据'),
          },
          {
            value: '3',
            label: this.translateTitle('Ve.elements.全量数据'),
          },
        ],
        optionsDetail: [
          {
            value: '1',
            label: this.translateTitle('Ve.elements.是'),
          },
          {
            value: '2',
            label: this.translateTitle('Ve.elements.否'),
          },
        ],
        showModal: false,
        subForm: {
          type: '1',
          isDetail: '1',
          '#EXPORT_WHERE#': {},
          '#EXPORT_SQL_ID#': 'dams.handle.flow.table.query',
          '#EXPORT_API_NAME#': 'dams.handle.flow.query',
          '#QUERY_SORT#': {
            // API_NAME: 'desc',
          },
          '#EXPORT_FILE_NAME#': '',
          '#EXPORT_FILE_TYPE#': 'xlsx',
          '#EXPORT_SHEET_NAME#': '',
          '#EXPORT_COLUMN#': {},
        },
        tableOptions: [],
        columnsData: [],
        isMultistage: false, //是否多级
      }
    },
    computed: {},
    methods: {
      notIsCheck(list, data) {
        for (let index = 0; index < data.length; index++) {
          const element = data[index]
          if (element && !list.find((el) => el == element._id) && element._isChecked == true) {
            element._isChecked = false
          }
          if (element && element.children) {
            this.notIsCheck(list, element.children)
          }
        }
      },
      setNewTreeTest(list) {
        for (let index = 0; index < list.length; index++) {
          const element = list[index]
          if (!element._isChecked) {
            list.splice(index, 1)
            index--
          }
          if (element.children) {
            this.setNewTreeTest(element.children)
          }
        }
      },
      handleCheckChange(data, { checkedKeys, halfCheckedKeys, checkedNodes, halfCheckedNodes }) {
        console.log(checkedKeys, halfCheckedKeys, checkedNodes, halfCheckedNodes)
        checkedNodes.forEach((r) => {
          r._isChecked = true
        })
        halfCheckedNodes.forEach((r) => {
          r._isChecked = true
        })
        const checkList = checkedKeys.concat(halfCheckedKeys)
        this.notIsCheck(checkList, this.treeData)
      },
      translateTitle,
      getColumns() {
        this.tableOptions = []
        let tableList = this.info.extension.setParam.value || this.info.extension.getTable
        let typeList = ['field', 'tag', 'image', 'progress', 'switch']
        tableList.forEach((row) => {
          let arr = this.vuiComponents[row.selectTable.value[0]]?.self?.$getTableColumns().filter((el) => typeList.indexOf(el._type) > -1)
          arr.forEach((r) => {
            r.checked = true
          })
          console.log(arr)
          console.log(this.vuiComponents[row.selectTable.value[0]])
          this.tableOptions.push({
            name: this.vuiComponents[row.selectTable.value[0]].self.getInfo.name,
            _id: row.selectTable.value[0],
            bindForm: row?.selectForm?.value,
            list: arr,
            '#EXPORT_API_NAME#': row['#EXPORT_API_NAME#'],
            '#EXPORT_SQL_ID#': row['#EXPORT_SQL_ID#'],
            '#EXPORT_SHEET_NAME#': row['#EXPORT_SHEET_NAME#'],
            addKey: row.addKey,
            order: row.order,
            Strkey: row.Strkey ? row.Strkey : '',
            sort: this.setSort(row.sort), //暂时只有一个
          })
        })
        this.subForm.tableId = this.tableOptions.length ? this.tableOptions[0]._id : ''
        this.columnsData = this.tableOptions.length ? this.tableOptions[0].list : '' //value[0].neglect
        console.log(this.tableOptions, this.info.extension.setParam)
        let list = []
        if (this.tableOptions.length && this.tableOptions[0].list) {
          this.tableOptions[0].list.forEach((row) => {
            if (!this.info.extension.setParam.value[0]?.neglect?.find((el) => el == row.field)) {
              list.push(row)
            }
          })
        }
        this.columnsData = list
        this.treeData = this.tableOptions[0].list
        this.tableOptions[0].list.forEach((r) => {
          if (r.children && r.children.length > 0) {
            this.isMultistage = true
          }
        })
        if (this.isMultistage) {
          this.$nextTick(() => {
            //这个如果要默认全选就必须加，否则会报错“setCheckedNodes”未定义
            this.$refs.channelTree.setCheckedNodes(this.treeData)
            this.setTree(this.treeData)
          })
        }
      },
      setTree(data) {
        data.forEach((r) => {
          r._isChecked = true
          if (r.children) {
            this.setTree(r.children)
          }
        })
      },
      setSort(obj) {
        if (!obj) return {}
        let result = {}
        result[obj.key] = obj.value
        return result
      },
      tableChange(e) {
        console.log(e)
        let oldList = this.tableOptions.find((el) => el._id == e).list
        let list = []
        oldList.forEach((row) => {
          if (!this.info.extension.setParam.value[0].neglect.find((el) => el == row.field)) {
            list.push(row)
          }
        })
        // }
        this.columnsData = list
      },
      //打开下载弹框
      openDownload() {
        if (!this.hasPreview) {
          console.log('预览模式不运行 onClick')
          return
        }
        this.isMultistage = false
        this.showModal = true
        this.getColumns()
      },
      //json格式化
      formatJson(filterVal, jsonData) {
        jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
        return jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
      },
      setFirstLineData(filterVal, pageData) {
        let list = cloneDeep(pageData)
        if (this.info.extension['#WRITE_FIELD_ROWS#'].value) {
          let valObj = {}
          filterVal.forEach((row) => {
            valObj[row] = row
          })
          list.unshift(valObj)
          return list
        } else {
          return list
        }
      },
      downloadSave(arr) {
        if (this.subForm.isDetail == '2') {
          arr = [arr[0]]
        }
        //调用接口下载
        request({
          url:
            GFCD('dams', 'domain') +
            (this.info.extension.apiUrl && this.info.extension.apiUrl.value
              ? this.info.extension.apiUrl.value
              : this.$store.getters['user/appCodeUrl']),
          method: 'post',
          data: {
            data: JSON.stringify(arr),
            method: this.info.extension.apiMethod.value,
          },
          responseType: 'blob',
        }).then((res) => {
          console.log(res)
          let transStr = this.translateTitle('Ve.elements.导出文件')
          let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime() + '.xlsx'
            a.href = e.target.result
            a.click()
            this.showModal = false
          }
        })
      },
      setParameter(arr, pageData) {
        let strKey = this.tableOptions[0].Strkey
        console.log(strKey)
        if (strKey) {
          for (let index = 0; index < strKey.length; index++) {
            const element = strKey[index]
            arr.forEach((r) => {
              if (pageData && pageData.length > 0) {
                r['#EXPORT_WHERE#'][element] = pageData.map((el) => el[element]).join(',')
              }
              if (!pageData && this.subForm.isDetail == '1') {
                r['#EXPORT_WHERE#'][element] = 'ALL'
              }
            })
            // arr[0]['#EXPORT_WHERE#'][element] = pageData.map((el) => el[element]).join(',')
          }
        }
        return arr
      },
      save() {
        //勾选了的表头
        // let arr = []
        this.tableOptions.forEach((row) => {
          row.obj = {}
          row.addKey &&
            row.addKey.forEach((r) => {
              if (!row.list.find((el) => el.field == r.field)) {
                if (row?.order == '1') {
                  row.list.unshift(r)
                }
                if (row?.order == '2') {
                  row.list.push(r)
                }
              }
            })
          row.list
            .filter((el) => el.checked || el.checked === undefined)
            .forEach((i) => {
              if (!this.info.extension.setParam.value[0]?.neglect?.find((el) => el == i.field)) {
                row.obj[i.field] = i.title
              }
            })
        })
        let formInfo = this.info.extension.getFrom
        let tableInfo = this.info.extension.setParam
        console.log(formInfo)
        this.tableOptions.forEach((row) => {
          console.log(row)
          row.subFromData = {}
          if (row.bindForm) {
            if (row.bindForm.length > 0) {
              if (this.vuiComponents[row.bindForm[0]].self.getInfo.type == 'uiTable') {
                row.subFromData = this.vuiComponents[row.bindForm[0]].self.getCheckboxOrRadioVals()[0]
                  ? cloneDeep(this.vuiComponents[row.bindForm[0]].self.getCheckboxOrRadioVals()[0])
                  : {}
              } else {
                row.subFromData = cloneDeep(this.vuiComponents[row.bindForm[0]].ref.model)
              }
              console.log(row.subFromData)
              if (this.info.extension?.keyInterchange && this.info.extension?.keyInterchange?.value) {
                this.info.extension.keyInterchange.value.forEach((r) => {
                  row.subFromData[r.key] = r.value
                })
              }
            }
          }
          if (!row.bindForm) {
            //搜索表单数据
            if (formInfo?.value.length > 0) {
              if (this.vuiComponents[formInfo?.value[0]].self.getInfo.type == 'uiTable') {
                row.subFromData = cloneDeep(this.vuiComponents[formInfo?.value[0]].self.getCheckboxOrRadioVals()[0])
              } else {
                row.subFromData = cloneDeep(this.vuiComponents[formInfo?.value[0]].ref.model)
              }
              if (this.info.extension?.keyInterchange && this.info.extension?.keyInterchange?.value) {
                this.info.extension.keyInterchange.value.forEach((r) => {
                  row.subFromData[r.key] = r.value
                })
              }
            }
          }
        })
        console.log('this.tableOptions=======', this.tableOptions)
        //搜索表单数据
        // let subFromData
        // if (formInfo?.value.length > 0) {
        //   if (this.vuiComponents[formInfo?.value[0]].self.getInfo.type == 'uiTable') {
        //     subFromData = this.vuiComponents[formInfo?.value[0]].self.getCheckboxOrRadioVals()[0]
        //   } else {
        //     subFromData = this.vuiComponents[formInfo?.value[0]].ref.model
        //   }
        //   if (this.info.extension.keyInterchange && this.info.extension.keyInterchange.value) {
        //     this.info.extension.keyInterchange.value.forEach((row) => {
        //       // if (subFromData[row.key]) {
        //       //   subFromData[row.key] = row.value
        //       // } else{
        //       subFromData[row.key] = row.value
        //       // }
        //     })
        //   }
        // }
        // console.log(subFromData)
        //表格本页数据
        // let pageData = this.vuiComponents[tableInfo.value[0]].self.list
        let pageData = this.vuiComponents[tableInfo.value[0].selectTable.value[0]].self.list
        //表格选中数据
        let checkboxData = this.vuiComponents[tableInfo.value[0].selectTable.value[0]].ref.getCheckboxRecords()
        let list = []
        if (this.tableOptions.length && this.tableOptions[0].list) {
          this.tableOptions[0].list.forEach((row) => {
            if (!this.info.extension.setParam.value[0]?.neglect?.find((el) => el == row.field)) {
              list.push(row)
            }
          })
        }
        console.log(this.tableOptions)
        const multiHeader = list.filter((el) => el.checked || el.checked === undefined).map((el) => el.title) //表头显示
        const filterVal = list.filter((el) => el.checked || el.checked === undefined).map((el) => el.field) //表头所对应后台返回的字段
        let data
        if (this.subForm.type == '3') {
          let arr = []
          let transStr = this.translateTitle('Ve.elements.导出文件')
          this.tableOptions.forEach((row) => {
            arr.push({
              '#EXPORT_WHERE#': row.subFromData ? row.subFromData : {},
              '#WRITE_FIELD_ROWS#': this.info.extension['#WRITE_FIELD_ROWS#'].value ? 'Y' : 'N',
              '#QUERY_SORT#': row.sort ? row.sort : this.vuiComponents[row._id].self.sortType ? this.vuiComponents[row._id].self.sortType : {},
              '#EXPORT_SQL_ID#': row['#EXPORT_SQL_ID#'],
              '#EXPORT_API_NAME#': row['#EXPORT_API_NAME#'],
              '#EXPORT_COLUMN#': row.obj,
              '#EXPORT_SHEET_NAME#': row['#EXPORT_SHEET_NAME#'] || '',
              '#EXPORT_FILE_NAME#': this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime(),
            })
          })
          arr = this.setParameter(arr)
          this.downloadSave(arr)
        } else {
          if (this.info.extension?.detailDownload?.value && this.subForm.isDetail == '1') {
            //需要多sheet导出
            let arr = []
            let transStr = this.translateTitle('Ve.elements.导出文件')
            this.tableOptions.forEach((row) => {
              arr.push({
                '#EXPORT_WHERE#': row.subFromData ? row.subFromData : {},
                '#WRITE_FIELD_ROWS#': this.info.extension['#WRITE_FIELD_ROWS#'].value ? 'Y' : 'N',
                '#QUERY_SORT#': row.sort ? row.sort : this.vuiComponents[row._id].self.sortType ? this.vuiComponents[row._id].self.sortType : {},
                '#EXPORT_SQL_ID#': row['#EXPORT_SQL_ID#'],
                '#EXPORT_API_NAME#': row['#EXPORT_API_NAME#'],
                '#EXPORT_COLUMN#': row.obj,
                '#EXPORT_SHEET_NAME#': row['#EXPORT_SHEET_NAME#'] || '',
                '#EXPORT_FILE_NAME#': this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime(),
              })
            })
            if (this.subForm.type == '1') {
              arr = this.setParameter(arr, pageData)
            } else {
              arr = this.setParameter(arr, checkboxData)
            }
            this.downloadSave(arr)
          } else {
            let list = cloneDeep(this.treeData)
            console.log(cloneDeep(list))
            this.setNewTreeTest(list)
            console.log(cloneDeep(list))
            //前端下载
            let transStr = this.translateTitle('Ve.elements.导出文件')
            if (this.isMultistage) {
              if (this.subForm.type == '1') {
                if (pageData.length == 0) return this.$baseMessage(`暂无数据`, 'error')
                // data = this.formatJson(filterVal, this.setFirstLineData(filterVal, pageData))
                exportData(
                  pageData,
                  list,
                  this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime()
                )
                //本页数据格式化
              } else {
                if (checkboxData.length == 0) return this.$baseMessage(`请选择数据`, 'error')
                // data = this.formatJson(filterVal, this.setFirstLineData(filterVal, checkboxData))
                exportData(
                  checkboxData,
                  list,
                  this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime()
                )
              }
            } else {
              if (this.subForm.type == '1') {
                if (pageData.length == 0) return this.$baseMessage(`暂无数据`, 'error')
                data = this.formatJson(filterVal, this.setFirstLineData(filterVal, pageData))
                //本页数据格式化
              } else {
                if (checkboxData.length == 0) return this.$baseMessage(`请选择数据`, 'error')
                data = this.formatJson(filterVal, this.setFirstLineData(filterVal, checkboxData))
              }
              export_json_to_excel({
                multiHeader, //这里是第一行的表头
                data, //数据
                filename: this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime(),
                bookType: 'xlsx',
              })
            }
            console.log(this.tableOptions[0].list, pageData)
            //前端下载
            // if (this.subForm.type == '1') {
            //   if (pageData.length == 0) return this.$baseMessage(`暂无数据`, 'error')
            //   data = this.formatJson(filterVal, this.setFirstLineData(filterVal, pageData))
            //   //本页数据格式化
            // } else {
            //   if (checkboxData.length == 0) return this.$baseMessage(`请选择数据`, 'error')
            //   data = this.formatJson(filterVal, this.setFirstLineData(filterVal, checkboxData))
            // }
            // exportData(pageData, this.tableOptions[0].list)
            // let transStr = this.translateTitle('Ve.elements.导出文件')
            // let btn = false
            // if (btn) {
            // export_json_to_excel({
            //   multiHeader, //这里是第一行的表头
            //   data, //数据
            //   filename: this.subForm['#EXPORT_FILE_NAME#'] ? this.subForm['#EXPORT_FILE_NAME#'] : transStr + '_' + new Date().getTime(),
            //   bookType: 'xlsx',
            // })

            this.showModal = false
            // }
          }
        }
      },
    },
  })
</script>
<style scoped>
  .ui-button {
    padding-top: 3px;
  }
</style>
